package org.jeecg.modules.asset.controller;

import java.text.DecimalFormat;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.DateUtils;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.asset.entity.AssetLedger;
import org.jeecg.modules.asset.service.IAssetLedgerService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

 /**
 * @Description: 资产台账
 * @Author: jeecg-boot
 * @Date:   2025-11-02
 * @Version: V1.0
 */
@Api(tags="资产台账")
@RestController
@RequestMapping("/asset/assetLedger")
@Slf4j
public class AssetLedgerController extends JeecgController<AssetLedger, IAssetLedgerService> {
	@Autowired
	private IAssetLedgerService assetLedgerService;
	
	/**
	 * 分页列表查询
	 *
	 * @param assetLedger
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "资产台账-分页列表查询")
	@ApiOperation(value="资产台账-分页列表查询", notes="资产台账-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<AssetLedger>> queryPageList(AssetLedger assetLedger,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<AssetLedger> queryWrapper = QueryGenerator.initQueryWrapper(assetLedger, req.getParameterMap());
		Page<AssetLedger> page = new Page<AssetLedger>(pageNo, pageSize);
		IPage<AssetLedger> pageList = assetLedgerService.page(page, queryWrapper);
		return Result.OK(pageList);
	}
	
	/**
	 *   添加
	 *
	 * @param assetLedger
	 * @return
	 */
	@AutoLog(value = "资产台账-添加")
	@ApiOperation(value="资产台账-添加", notes="资产台账-添加")
	//@RequiresPermissions("org.jeecg.modules:asset_ledger:add")
	@PostMapping(value = "/add")
	public Result<String> add(@RequestBody AssetLedger assetLedger) {
		long count = assetLedgerService.count()+1;
		// count 不足4位前面补0
		String countStr = String.format("%04d", count);
		// 三位随机数字
		assetLedger.setCode("ZC-"+ DateUtils.getYear() + countStr);
		assetLedgerService.save(assetLedger);
		return Result.OK("添加成功！");
	}
	
	/**
	 *  编辑
	 *
	 * @param assetLedger
	 * @return
	 */
	@AutoLog(value = "资产台账-编辑")
	@ApiOperation(value="资产台账-编辑", notes="资产台账-编辑")
	//@RequiresPermissions("org.jeecg.modules:asset_ledger:edit")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> edit(@RequestBody AssetLedger assetLedger) {
		assetLedgerService.updateById(assetLedger);
		return Result.OK("编辑成功!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "资产台账-通过id删除")
	@ApiOperation(value="资产台账-通过id删除", notes="资产台账-通过id删除")
	//@RequiresPermissions("org.jeecg.modules:asset_ledger:delete")
	@DeleteMapping(value = "/delete")
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {
		assetLedgerService.removeById(id);
		return Result.OK("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "资产台账-批量删除")
	@ApiOperation(value="资产台账-批量删除", notes="资产台账-批量删除")
	//@RequiresPermissions("org.jeecg.modules:asset_ledger:deleteBatch")
	@DeleteMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.assetLedgerService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "资产台账-通过id查询")
	@ApiOperation(value="资产台账-通过id查询", notes="资产台账-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<AssetLedger> queryById(@RequestParam(name="id",required=true) String id) {
		AssetLedger assetLedger = assetLedgerService.getById(id);
		if(assetLedger==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(assetLedger);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param assetLedger
    */
    //@RequiresPermissions("org.jeecg.modules:asset_ledger:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, AssetLedger assetLedger) {
        return super.exportXls(request, assetLedger, AssetLedger.class, "资产台账");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    //@RequiresPermissions("asset_ledger:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, AssetLedger.class);
    }


	 /**
	  * 四张卡片统计
	  */
	 @ApiOperation(value="资产台账-四张卡片统计", notes="资产台账-四张卡片统计")
	 @GetMapping(value = "/cardTotal")
	 public Result<Map<String, Object>> cardTotal() {
		 Map<String, Object> map = new HashMap<>();
		 QueryWrapper<AssetLedger> queryWrapper = new QueryWrapper<>();
		 // 空间资产数量
		 List<AssetLedger> spaceAssetList = assetLedgerService.list(queryWrapper.eq("type", 1));
		 map.put("spaceAssetTotal", spaceAssetList.size());
		 // 设备资产数量
		 queryWrapper.clear();
		 List<AssetLedger> equipAssetList = assetLedgerService.list(queryWrapper.eq("type", 2));
		 map.put("equipAssetTotal", equipAssetList.size());
		 // 空间使用率 获取 status为1（运营状态），floorArea求和
		 double usedFloorArea = spaceAssetList.stream()
				 .filter(asset -> asset.getFloorArea() != null && asset.getStatus().equals("1"))
				 .mapToDouble(asset -> Double.parseDouble(asset.getFloorArea()))
				 .sum();
		 double allFloorArea = spaceAssetList.stream()
				 .filter(asset -> asset.getFloorArea() != null)
				 .mapToDouble(asset -> Double.parseDouble(asset.getFloorArea()))
				 .sum();
		 if (allFloorArea != 0){
			 //百分比 保留两位小数
			 map.put("spaceUseRate", new DecimalFormat("0.00").format(usedFloorArea / allFloorArea * 100));
		 }else {
			 map.put("spaceUseRate", 0);
		 }

		 // 设备使用率
		 // 空间使用率 获取 status为1（运营状态），floorArea求和
		 double usedEquipSize = equipAssetList.stream()
				 .filter(asset -> asset.getStatus().equals("1")).collect(Collectors.toList()).size();
		 if (allFloorArea != 0){
			 //百分比 保留两位小数
			 map.put("equipGoodRate", new DecimalFormat("0.00").format(usedEquipSize * 100 / equipAssetList.size()));
		 }else {
			 map.put("equipGoodRate", 0);
		 }
		 return Result.OK(map);
	 }


	 /**
	  * 首页统计
	  */
	 @ApiOperation(value="资产台账-首页统计", notes="资产台账-首页统计")
	 @GetMapping(value = "/indexTotal")
	 public Result<Map<String, Object>> indexTotal() {
		 Map<String, Object> map = new HashMap<>();
		 QueryWrapper<AssetLedger> queryWrapper = new QueryWrapper<>();
		 // 总资产数量
		 List<AssetLedger> assetList = assetLedgerService.list(queryWrapper);
		 map.put("assetTotal", assetList.size());
		 // 运营中资产
		 queryWrapper.clear();
		 long useAsset = assetLedgerService.count(queryWrapper.eq("status", 1));
		 map.put("useAssetTotal", useAsset);
		 // 使用率
		 if (assetList.size() != 0){
			 map.put("useRate", new DecimalFormat("0.0").format(useAsset * 100 / assetList.size()));
		 }else {
			 map.put("useRate", 0);
		 }
		 // 闲置资产
		 queryWrapper.clear();
		 long leaveNum = assetLedgerService.count(queryWrapper.eq("status", 2));
		 map.put("leaveAssetTotal", leaveNum);
		 // 总建筑面积 获取 status为1（运营状态），floorArea求和
		 double allFloorArea = assetList.stream()
				 .filter(asset -> asset.getFloorArea() != null)
				 .mapToDouble(asset -> Double.parseDouble(asset.getFloorArea()))
				 .sum();
		 map.put("floorArea", allFloorArea);
		 return Result.OK(map);
	 }
}
